<%#
 Copyright 2018-2019 Lienol <lawlienol@gmail.com>
 Licensed to the public under the Apache License 2.0.
-%>
<%
local dsp = require "luci.dispatcher"
-%>
<script type="text/javascript">
	//<![CDATA[
	const doms = document.getElementsByClassName('pingtime');
	const ports = document.getElementsByClassName("socket-connected")
	// 这也是卡的原罪 CGI 一下子处理不这么多
	const xhr = (index) => {
		return new Promise((res) => {
			const dom = doms[index];
			const port = ports[index];
			if (!dom) res()
			XHR.get('<%=dsp.build_url("admin/services/shadowsocksr/ping")%>', {
				index,
				domain: dom.getAttribute("hint"),
				port: port.getAttribute("hint")
			},
			(x, result) => {
				let col = '#ff0000';
				if (result.ping) {
					if (result.ping < 300) col = '#ff3300';
					if (result.ping < 200) col = '#ff7700';
					if (result.ping < 100) col = '#249400';
				}
				dom.innerHTML = `<font color="${col}">${(result.ping ? result.ping : "--") + " ms"}</font>`
				if (result.socket) {
					port.innerHTML = '<font color="#249400">ok</font>'
				} else {
					port.innerHTML = '<font color="#ff0000">fail</font>'
				}
				res()
			});
		})
	}
	(async () => {
		for (let group = 0; group < Math.ceil(doms.length / 5); group++) {
			await Promise.all([
				xhr(group * 5 + 0),
				xhr(group * 5 + 1),
				xhr(group * 5 + 2),
				xhr(group * 5 + 3),
				xhr(group * 5 + 4),
			])
		}
	})()
	// for(var i = 0; i < pings.length; i++) {
	// 	XHR.get('<%=dsp.build_url("admin/services/shadowsocksr/ping")%>', {
	// 			index: i,
	// 			domain: pings[i].getAttribute("hint")
	// 		},
	// 		function(x, result) {
	// 			pings[result.index].innerHTML = (result.ping ? result.ping : "--") + " ms";
	// 		}
	// 	);
	// }
	//]]>
</script>